/*
 * MonthChargingEventResource.cpp
 *
 *  Created on: 2014. 3. 5.
 *      Author: mega
 */

#include "../User.h"
#include "../NUtil/Utils.h"
#include <Toolkit/Str.h>
#include <Database/Static.h>
#include "Static.h"
#include "MonthChargingEventResource.h"

namespace ProjectZ { namespace NResource {

MonthChargingEventResource::MonthChargingEventResource()
{
	pMonthChargingAD	= new MonthChargingEvent;
	pMonthChargingIOS	= new MonthChargingEvent;
}

MonthChargingEventResource::~MonthChargingEventResource()
{
	delete pMonthChargingAD;
	delete pMonthChargingIOS;
}

MonthChargingEventResource::MonthChargingEvent::MonthChargingEvent()
{

}

MonthChargingEventResource::MonthChargingEvent::~MonthChargingEvent()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](MONTHCHARGINGTREE::value_type & pair) {
		delete pair.second;
	});
}

void
MonthChargingEventResource::MonthChargingEvent::Clear()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](MONTHCHARGINGTREE::value_type & pair) {
		delete pair.second;
	});
	clsFlyTree.clear();
}

bool
MonthChargingEventResource::LoadResource()
{
	if (false == pMonthChargingAD->LoadResource(MARKET_GOOGLE, SC_KAKAO_GOOGLE))
		return false;

	if (false == pMonthChargingIOS->LoadResource(MARKET_IOS, SC_KAKAO_IOS))
		return false;

	return true;
}

bool
MonthChargingEventResource::MonthChargingEvent::LoadResource(int company, int salecode)
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT NATIONAL_CODE, SEQ, ITEM_SHEET, ITEM_TID, ITEM_QUANTITY, URL, UNIX_TIMESTAMP(START_DATE), UNIX_TIMESTAMP(END_DATE) FROM resource_month_charging_event WHERE COMPANY = %d AND SALE_CODE = %d", company, salecode);

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		Flyweight * pFly = new Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_SEQ >> pFly->_ITEM_SHEET >> pFly->_ITEM_TID >> pFly->_ITEM_QUANTITY
				>> pFly->_URL >> pFly->_START_DATE >> pFly->_END_DATE;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyTree[pFly->_SEQ] = pFly;
	}

	return true;
}

MonthChargingEventResource::MonthChargingEvent::Flyweight *
MonthChargingEventResource::GetFly(User * pUser)
{
	NUtil::MarketType marketType = NUtil::GetMarketType(pUser->GetCompany(), pUser->GetSaleCode());

	switch (marketType)
	{
	case NUtil::MarketType::AD_KAKAO:
		return pMonthChargingAD->GetFly();

	case NUtil::MarketType::IOS_KAKAO:
		return pMonthChargingIOS->GetFly();

	default:
		return NULL;
	}

	return NULL;
}

MonthChargingEventResource::MonthChargingEvent::Flyweight *
MonthChargingEventResource::MonthChargingEvent::GetFly()
{
	time_t curTime = time(NULL);

	auto iter = clsFlyTree.begin();
	for (; iter != clsFlyTree.end(); iter++)
	{
		Flyweight * pFly = iter->second;

		if (pFly->_START_DATE <= curTime && curTime <= pFly->_END_DATE)
		{
			return pFly;
		}
	}

	return NULL;

#if 0
	int lastSeq = 0;
	time_t tmpTime = 0;

	iter = clsFlyTree.begin();
	for (; iter != clsFlyTree.end(); iter++)
	{
		Flyweight * pFly = iter->second;

		// 시작시간이 현재시간보다 이후인 경우 SKIP!
		if (pFly->_START_DATE > curTime)
			continue;

		// 가장 최근 데이터를 찾는다
		if (pFly->_START_DATE > tmpTime)
		{
			lastSeq = pFly->_SEQ;
			tmpTime = pFly->_START_DATE;
		}
	}

	// 이번달에 이벤트가 등록되어 있지 않은 경우 가장 최근 이벤트로 진행
	{
		auto iter = clsFlyTree.find(lastSeq);

		if (iter == clsFlyTree.end())
			return NULL;

		return iter->second;
	}
#endif
}

bool
MonthChargingEventResource::IsRecvMonthChargeEventItem(User * pUser)
{
	MonthChargingEvent::Flyweight * pFly = Static::Instance().GetMonthChargingResource()->GetFly(pUser);
	if (NULL == pFly)
	{
		return true;
	}

	time_t lastChargeTime = static_cast<time_t>(pUser->GetUserInfo().reserve3);

	// 이벤트 기간내 구매한 경우
	if (pFly->_START_DATE <= lastChargeTime && lastChargeTime <= pFly->_END_DATE)
	{
		return true;
	}

	return false;

//	time_t initTime = NLogic::NFunction::GetMonthInitTime();
//
//	TESTLOG("%s : Init Time=%ld, User Charge Time=%ld", __FUNCTION__, initTime, pUser->GetUserInfo().reserve3);
//
//	if (initTime <= static_cast<time_t>(pUser->GetUserInfo().reserve3))
//	{
//		return false;
//	}
//
//	return true;
}

void
MonthChargingEventResource::SendMonthChargeEventItem(User * pUser)
{
	if (true == this->IsRecvMonthChargeEventItem(pUser))
	{
		return;
	}

	MonthChargingEvent::Flyweight * pFly = Static::Instance().GetMonthChargingResource()->GetFly(pUser);
	if (NULL == pFly)
	{
		return;
	}

	NLogic::MailBox::Mail::Data clsMailData;
	clsMailData.send_user_seq		= 0;
	clsMailData.send_user_nickname	= "GAMEVIL";
	clsMailData.recv_user_seq		= pUser->GetUserSeq();
	clsMailData.message				= Static::InstancePtr()->GetMailMessageResource()->GetMessageMonthChargingEventReward();
	clsMailData.gift_status			= EM_GIFT_ITEM;

	NLogic::Item::Data clsItemData;
	clsItemData.tid			= pFly->_ITEM_TID;
	clsItemData.sub_type	= pFly->_ITEM_SHEET;
	clsItemData.class_type	= -1;

	int isStack = Static::InstancePtr()->GetItemResource()->getItemStackType(clsItemData);

	int sendMailCount	= 0;
	int itemQuantity	= 0;

	// 스택 아이템이 아니면서, 보상 수량이 2개 이상인 경우는 아이템을 하나씩 첨부하여 메일을 각각 발송한다.
	if (1 != isStack && pFly->_ITEM_QUANTITY >= 2)
	{
		itemQuantity	= 1;
		sendMailCount	= pFly->_ITEM_QUANTITY;
	}
	else
	{
		itemQuantity	= pFly->_ITEM_QUANTITY;
		sendMailCount	= 1;
	}

	if (false == Static::InstancePtr()->GetItemResource()->SetItemFromXLS(pUser, clsMailData.item, pFly->_ITEM_SHEET, pFly->_ITEM_TID, itemQuantity))
	{
		DEBUGLOG("%s : ITEM Setting Fail!!", __FUNCTION__);
		return;
	}

	for (int i = 0; i < sendMailCount; i++)
	{
		if (false == NLogic::NFunction::SendMail(pUser, clsMailData))
		{
			DEBUGLOG("%s : ITEM Mail Send Fail!!", __FUNCTION__);
			return;
		}
	}
}

} /*NResource*/ } /*ProjectZ*/
